package neichuan.server.browser;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class BrowserServer {

    ServerBootstrap sb;
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    public BrowserServer(){

    }

    public Channel addServer(int port) throws InterruptedException {
        if(sb==null){
            init();
        }
        ChannelFuture f = sb.bind(port);
        f.sync();
        return f.channel();
    }

    private void init(){
        bossGroup=new NioEventLoopGroup();
        workerGroup=new NioEventLoopGroup();
        sb=new ServerBootstrap();
        sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        setChildHandler(sb);
        setOption(sb);
        setChildOption(sb);
    }

    public void close(){
        if(workerGroup!=null){
            workerGroup.shutdownGracefully();
        }
        if(bossGroup!=null){
            bossGroup.shutdownGracefully();
        }
    }




    protected void setChildHandler(ServerBootstrap sb) {


        sb.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new BrowserServerHandler());
            }
        });
    }

    protected void setOption(ServerBootstrap sb){
//        sb.option(ChannelOption.SO_BACKLOG, 128);
    }

    protected void setChildOption(ServerBootstrap sb){
//        sb.childOption(ChannelOption.SO_KEEPALIVE, true);
    }
}
